<?php
/**
 * Created by PhpStorm.
 * User: 珊珊
 * Date: 2018/6/3
 * Time: 22:31
 */

namespace app\portal\model;
use think\Model;
use think\db;

class ClanModel extends Model
{
    public function getParentList($page = 1, $pageSize = 6)
    {
        $offset = 0;
		$limit = $pageSize;
		if($page > 1){
			$offset = ($page - 1) * $pageSize;
			$limit = $page * $pageSize;
		}
		$count = $this->where(['parent_id'=>0, 'level'=>0, 'is_deleted'=>0])->count('id');
		$list = $this->where(['parent_id'=>0, 'level'=>0, 'is_deleted'=>0])->field('id,name,detail')->limit($offset, $limit)->select()->toArray();
		foreach($list as $k => $v){
			$list[$k]['detail'] = html_entity_decode($v['detail']);
		}
		$data['page'] = $page;
		$data['last'] = $count <= $limit;
		$data['list'] = $list;
		return $data;
    }
	
	public function getFangList($pId, $page = 1, $keyword = '', $pageSize = 8)
    {
        $offset = 0;
		$limit = $pageSize;
		if($page > 1){
			$offset = ($page - 1) * $pageSize;
			$limit = $page * $pageSize;
		}
        $where  = ['parent_id'=>$pId, 'level'=>1, 'is_deleted'=>0];
        $data['title'] = $this->where('id', $pId)->value('name');
		if(!(empty($keyword) || $keyword == null)) {
             $memberClan = Db::name('member')->alias('m')
                 ->join('clan c','m.clan_id = c.id')
                 ->where('m.name|m.style_name','like','%'.$keyword.'%')
                 ->where('m.clan_id','gt',0)
                 ->column('c.level', 'm.clan_id');
            $l1 = array_filter($memberClan,function ($v) {
                if($v == 1)
                    return 1;
                else
                    return 0;
            });
            $l1 = array_keys($l1);
            $l2 = array_filter($memberClan,function ($v) {
                if($v == 2)
                    return 1;
                else
                    return 0;
            });
            $l2 = array_keys($l2);
            $memberClan2 = Db::name('clan')->where('is_deleted', 'eq', 0)->where('id', 'in', $l2)->column('parent_id');
            $clan = array_merge($l1,$memberClan2);
            if (count($clan) > 0) {
                $where  = ['id'=>['in', $clan], 'level'=>1, 'is_deleted'=>0];
            }
            $data['title'] = '族谱';
        }
		$count = $this->where($where)->count('id');
		$list = $this->where($where)->field('id,name,img')->limit($offset, $limit)->select()->toArray();
		$data['page'] = $page;
		$data['last'] = $count <= $limit;
		$data['list'] = $list;
        $data['keyword'] = $keyword;
		return $data;
    }
	
	public function getLeverList($pId)
    {
		$list = $this->where(['parent_id'=>$pId, 'level'=>2, 'is_deleted'=>0])->field('id,name,img')->select()->toArray();
		return $list;
    }
}